


class Sql {

  constructor(){

  }

  sql = '';
  pms = '';


  print(){
    let sql = this.sql;
    const pms = this.pms.split(',');
    for(const i in pms){
      sql = sql.replace(/\?/, st => {
         const prefix = (sql.match(/\s+[^\s]+\s+[^\s]+\?/)||'').toString();
         let rpVal = pms[i].replace(/\([^\(\)]+\)/,'').replace(/^\s*(.*?)[\s\n]*$/g, '$1');
         if(!/limit/.test(prefix)){
            rpVal =  "'" + rpVal + "'";
         }
        return rpVal;
      });
    }
    return sql;
  }

}

const splitSql = (log) => {
  if(!log)
    return [];
  const sqls = [];
  for (const sp of log.split(/==>\s+Preparing:/)) {
    if(/==>\s+Parameters:/.test(sp)){
      const sqs = sp.split('\n');
      const sql = new Sql();
      sql.sql = sqs[0];
      for(const pm of sqs){
        if(/==>\s+Parameters:/.test(pm)){
          sql.pms = pm.split(/==>\s+Parameters:/)[1];
        }
      }
      sql.sql = sql.sql.trim();
      sql.pms = (sql.pms||'').trim();
      sqls.push(sql);
    }
  }
  const rtn = [];
  for (const sq of sqls) {
    rtn.push(sq.print());
  }
  return rtn;
}


export {
  splitSql
};
